package foo.workLlog.action;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import foo.base.BaseAction;
import foo.dbvo.WbsDbvo;
import foo.proj.bo.ProjBO;
import foo.proj.vo.ProjVvo;
import foo.proj.vo.WbsMaintainForm;
import foo.websystem.action.Consts;
import foo.websystem.bo.SystemBO;
import foo.workLlog.bo.WorkLogBO;
import foo.workLlog.vo.AjaxAutoCompleteReturnVvo;
import foo.workLlog.vo.WbsSelectForm;
import foo.workLlog.vo.WorkLogMaintainForm;
import foo.workLlog.vo.WorkLogVvo;

@Controller
@RequestMapping(value = "/workLog")
public class WorkLogAction extends BaseAction {
	@Autowired
	WorkLogBO workLogBO;
	private final String LIST_WORK_LOG = "/workLog/wo-r";
	private final static String PICK_WBS_PAGE = "/workLog/lov-task";
	private static final String QUICK_ADD_WBS_PAGE = "/workLog/wbs-c";
	@Autowired
	private SystemBO systemBO;
	@Autowired
	private ProjBO projBO;

	@RequestMapping(value = "/initFindWorkLog")
	public String initFindWorkLog(HttpSession session, Model model,
			WorkLogMaintainForm form) {
		try {
			// 產生預設查詢資料條件
			form.setEditWorkDate(Consts.DATE_FORMATER.format(new Date()));
			// 設定查詢條件初始值為系統日-1個月~系統日
			Calendar c = Calendar.getInstance();
			form.setSearchEndDate(Consts.DATE_FORMATER.format(c.getTime()));
			c.add(Calendar.MONTH, -1);
			form.setSearchStartDate(Consts.DATE_FORMATER.format(c.getTime()));
			model.addAttribute(Consts.MSG, "預設查詢登入人員一個月的資料");
		} catch (Exception e) {
			logger.error("初始WorkLog頁面m錯誤:", e);
			model.addAttribute(Consts.MSG, e.getLocalizedMessage());
		}
		initFindWorkLogPage(form, model, session);
		return LIST_WORK_LOG;
	}

	private void initFindWorkLogPage(WorkLogMaintainForm command, Model model,
			HttpSession session) {
		try {
			String userId = systemBO.getUser(session).getUserId();

			List<WorkLogVvo> list = workLogBO.findWorkLog(
					command.getSearchStartDate(), command.getSearchEndDate(),
					userId);
			// 產生頁面元件: 下拉選單
			LinkedHashMap<String, String> sysUsers = systemBO.getAllUserMap();
			model.addAttribute("sysUsers", sysUsers);
			model.addAttribute(list);
		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));
			model.addAttribute(Consts.MSG, "初始化頁面失敗:" + e.toString());
		}
	}

	@RequestMapping(value = "/maintainWorkLog", params = "searchWorkLog", method = RequestMethod.POST)
	public String findWorkLog(WorkLogMaintainForm workLogMaintainForm,
			Model model, HttpSession session) {
		try {
			logger.debug("執行: WorkLogAction.findWorkLog()");
			List<WorkLogVvo> list = new ArrayList<WorkLogVvo>();
			model.addAttribute(list);

		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackFrames(e));
			model.addAttribute(Consts.MSG, e.toString());
		}
		initFindWorkLogPage(workLogMaintainForm, model, session);
		return LIST_WORK_LOG;
	}

	@RequestMapping(value = "/maintainWorkLog", params = "addWorkLog")
	public String addWorkLog(WorkLogMaintainForm command, HttpSession session,
			Model model) {
		try {
			logger.debug("執行 /workLog/addWorkLog/: " + command);
			logger.debug(command);
			workLogBO.insertWorkLog(command.getEditWorkDate(),
					command.getEditWbsSn(), command.getEditWorkLogContent(),
					command.getEditHr(), command.getEditWorker());
			model.addAttribute(Consts.MSG, "新增完成");
		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));
			model.addAttribute(Consts.MSG, "新增失敗:" + e.toString());
		}
		initFindWorkLogPage(command, model, session);
		return LIST_WORK_LOG;
	}

	@RequestMapping("/initQuickAddWbs")
	public String initQuickAddWbs(Model model,
			@RequestParam("projSn") String projSn, WbsMaintainForm form) {
		try {
			Map<String, String> wbsTypes = projBO.findWbsTypeDropDown();
			model.addAttribute("wbsTypes", wbsTypes);
			ProjVvo projVvos = projBO.findProjsByPk(projSn);
			model.addAttribute(projVvos);
			model.addAttribute(form);
		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));
		}
		return QUICK_ADD_WBS_PAGE;
	}

	@RequestMapping(value = "/maintainWorkLog", params = "modifyWorkLog")
	public String modifyWorkLog(WorkLogMaintainForm command,
			HttpSession session, Model model) {
		try {
//			Enumeration<String> pms = request.getParameterNames();
//			while (pms.hasMoreElements()) {
//				String pm = pms.nextElement();
//				logger.debug(pm + ":" + request.getParameter(pm));
//			}
			logger.debug("執行 /workLog/modifyWorkLog/: " + command);
			logger.debug(command);
			workLogBO.updateWorkLog(command.getEditWorkLogSn(),
					command.getEditWorkDate(), command.getEditWbsSn(),
					command.getEditWorkLogContent(), command.getEditHr());

			model.addAttribute(Consts.MSG, "修改完成");
		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));
			model.addAttribute(Consts.MSG, "新增失敗:" + e.toString());
		}
		initFindWorkLogPage(command, model, session);
		return LIST_WORK_LOG;
	}

	@RequestMapping(value = "/quickAddWbs")
	public String quickAddWbs(Model model, WbsMaintainForm form,
			HttpSession session) {
		try {
			String projSn = form.getProjSn();
			String wbsName = form.getName();
			String wbsType = form.getTypeId();
			projBO.insertWbs(projSn, wbsName, form.getEstHr(), wbsType);
			WbsSelectForm wbsSelectForm = new WbsSelectForm();
			model.addAttribute(wbsSelectForm);
			wbsSelectForm.setProjSn(projSn);
			wbsSelectForm.setWbsName(wbsName);
			wbsSelectForm.setWbsTypeId(wbsType);
			initPickWbsPage(session, model, wbsSelectForm);
			return PICK_WBS_PAGE;
		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));
		}
		return QUICK_ADD_WBS_PAGE;
	}

	@RequestMapping("/initPickWbs")
	public String initPickWbs(HttpSession session, Model model,
			WbsSelectForm wbsSelectForm) {
		try {
			logger.debug("執行/workLog/initPickWbs");
			initPickWbsPage(session, model, wbsSelectForm);
		} catch (Exception e) {
			model.addAttribute(Consts.MSG, e.toString());
			logger.error(ExceptionUtils.getStackFrames(e));
		}
		return PICK_WBS_PAGE;
	}

	private void initPickWbsPage(HttpSession session, Model model,
			WbsSelectForm wbsSelectForm) {
		logger.debug("初始化WBS選取頁面元件(private initPickWbsPage ())");
		model.addAttribute(wbsSelectForm);
		Map<String, String> projs = projBO.findProjDropDown(systemBO.getUser(
				session).getUserId());
		model.addAttribute("projs", projs);
		Map<String, String> wbsTypes = projBO.findWbsTypeDropDown();
		model.addAttribute("wbsTypes", wbsTypes);
	}

	@RequestMapping("/pickWbsTask")
	public @ResponseBody
	List<AjaxAutoCompleteReturnVvo> pickWbsTask(
			@RequestParam("query") String searchWbsName, HttpSession session) {
		logger.debug("執行/pickWbsTask, searchWbsName:" + searchWbsName);
		try {
			return workLogBO.findPickWbsTaskNames(searchWbsName);
		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));
			return new ArrayList<AjaxAutoCompleteReturnVvo>();
		}
	}

	@RequestMapping(value = "/findWbs")
	public String findWbs(Model model, WbsSelectForm form, HttpSession session) {
		logger.debug("執行/workLog/findWbs, 輸入searchWbsName:" + form.getWbsName());
		try {
			List<WbsDbvo> wbses = workLogBO.findWbsByQuery(form.getProjSn(),
					form.getWbsName(), form.getWbsTypeId());
			model.addAttribute(wbses);
		} catch (Exception e1) {
			logger.error(ExceptionUtils.getStackFrames(e1));
			model.addAttribute(Consts.MSG, e1.toString());
		}
		try {
			initPickWbsPage(session, model, form);
		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackFrames(e));
			model.addAttribute(Consts.MSG, e.toString());
		}
		return PICK_WBS_PAGE;
	}

}
